package com.cslg.controller;

import com.alibaba.fastjson.JSON;
import com.cslg.pojo.Notice;
import com.cslg.pojo.User;
import com.cslg.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class NoticeController {
    @Autowired
    private NoticeService noticeService;
    @RequestMapping(value = "/selectByTop5Notice.do",produces = "text/application;charset=UTF-8")
    @ResponseBody
    public String selectByTop5Notice(){
        //调用service查询数据
        List<Notice> list = noticeService.selectTop5();
        list.forEach(li-> System.out.println(li));

        //将最后得到的数据封装成json格式的数据
        Map<String,Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", 0);
        map.put("data", list);

        String json = JSON.toJSONString(map);

        return json;
    }
    @RequestMapping(value = "/addNotice.do",produces = "text/application;charset=UTF-8")
    @ResponseBody
    public String addNotice(String json, HttpSession session){
        System.out.println("添加的数据："+json);
        //将json数据封装成User对象
        Notice notice = JSON.parseObject(json, Notice.class);
        User user = (User)session.getAttribute("user");
        if (user!=null){
            notice.setUserid(user.getId());
            //调用service层完成添加操作
            int i = noticeService.insertNotice(notice);
            return i+"";
        }
        return 0+"";
    }
}
